package cn.cys.service;

import cn.cys.properties.IpCountProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yiShan chen
 * @Date: 2023/3/31 11:00
 */
public class IpCountService {

    private final Map<String, Integer> ipCountMap = new HashMap<>();

    @Autowired
    private HttpServletRequest servletRequest;

    @Autowired
    private IpCountProperties ipCountProperties;


    /**
     * 统计ip
     */
    public void count() {
        String ip = servletRequest.getRemoteAddr();
        ipCountMap.put(ip, ipCountMap.getOrDefault(ip, 0) + 1);
    }

    /**
     * 报表打印
     */
    @Scheduled(cron = "0/#{ipCountProperties.cycle} * * * * ?")
    public void print() {
        System.out.println("         IP访问监控");
        if (IpCountProperties.ModelEnum.DETAIL.getValue().equals(ipCountProperties.getModel())) {
            System.out.println("+-----ip-address-----+--num--+");
            for (Map.Entry<String, Integer> entry : ipCountMap.entrySet()) {
                String key = entry.getKey();
                Integer value = entry.getValue();
                System.out.printf("|%18s  |%5d  |", key, value);
                System.out.println();
            }
            System.out.println("+--------------------+-------+");
        } else if (IpCountProperties.ModelEnum.SIMPLE.getValue().equals(ipCountProperties.getModel())) {
            System.out.println("+-----ip-address-----+");
            for (String key : ipCountMap.keySet()) {
                System.out.printf("|%18s  |", key);
                System.out.println();
            }
            System.out.println("+--------------------+");
        }
    }


}





